package com.example.blue_plugin;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class CheckPermissionListUtils {
    public static String[] checkPermissionList() {
        ArrayList<String> checkPermissionList = new ArrayList<>();
        //判断用户是否有授予蓝牙权限,适配android12
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            checkPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            checkPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
        }

        //判断用户是否有授予定位权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            checkPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        checkPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        String[] strings = new String[checkPermissionList.size()];
        for (int i = 0; i < checkPermissionList.size(); i++) {
            strings[i] = checkPermissionList.get(i);
        }
        Log.i("stf","-权限--->"+new Gson().toJson(strings));
        return strings;
    }

    public static void opt(Activity activity, OnRequestPermissionListener listener) {
        String[] permissions = checkPermissionList();
        List<String> mPermissionList = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(activity, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }

        Log.i("stf","-未通过的权限---->"+new Gson().toJson(mPermissionList));
        if (mPermissionList.isEmpty()) {// 全部允许
            listener.requestPermission(true);
        } else {//存在未允许的权限
            String[] permissionsArr = mPermissionList.toArray(new String[mPermissionList.size()]);
            ActivityCompat.requestPermissions(activity, permissionsArr, 101);
        }
    }

    public interface OnRequestPermissionListener {
        void requestPermission(boolean isFlag);
    }

}
